export default {
	data() {
		return {
			formItems: '',
			model: '',
			showDatePicker: false,
			datePickerModel: '',
			showTimePicker: false,
			timePickerModel: '',
			// provinceCityArea: ['11', '11007', '11007008'],
			// 获取验证码
			validateBtnDisabled: false,
			validateTips: '',
			showTrailerKeyboard: false,
			trailerNo: '',
			
		}
	},
	methods: {
		vehicleKeyboardConfirm: function(value) {
			this.model[this.currentProp] = value;
			this.showTrailerKeyboard = false;
		},

		handleCoustomFieldClick: function(item) {
			var vm = this;
			if (item.click) {
				var fooArr = item.click.split('_');
				var fooName = fooArr[0];
				if (fooName == 'addFields') { // 增加字段
					uni.showLoading({
						title: '请等待'
					});
					var addFormItems = JSON.parse(JSON.stringify(item.addFields));
					if (!item.extNum) {
						item.extNum = 1;
						item.uuid = vm.$Util.uuid(); // 起一个标识 删掉的时候要用
					}
					item.extNum++; // 计一个编号
					var propEndFix = '_' + item.extNum; // 下标
					var groupUuid = vm.$Util.uuid();
					addFormItems.forEach(n => {
						n.propId = item.uuid; // 所有此类型的uuid
						n.groupId = groupUuid; // 一组的id，以便按钮删除一组
					});
					var {
						rules,
						model
					} = formUtils.generateModelAndRules(addFormItems, '', propEndFix);
					var insertIndex = vm.formItems.findIndex(n => n == item);
					addFormItems[0].candelete = true;
					vm.formItems.splice(insertIndex, 0, ...addFormItems);
					vm.renameFileds(vm.formItems, item.uuid);

					var keys = Object.keys(model);
					keys.forEach((key) => {
						vm.$set(vm.model, key, model[key])
					});

					var rules2 = Object.assign(vm.rules, rules);
					vm.rules2 = rules2;
					// vm.$refs.form1.setRules(rules2);
					vm.$nextTick(function() {
						uni.hideLoading();
						vm.getRefCmp('form1').setRules(rules2);
					})
				} else {
					var fooArgs = fooArr.slice(1);
					vm[item.click](...fooArgs);
				}
			}
		},
		renameFileds(items) {
			var mapSet = {};
			items.forEach(n => {
				if (n.propId) {
					if (!mapSet[n.propId]) {
						mapSet[n.propId] = new Set();
					}
					mapSet[n.propId].add(n.groupId);
					var num = mapSet[n.propId].size + 1;
					if (!n.orignLabel) {
						n.orignLabel = n.label
					};
					n.label = n.orignLabel + num;
				}
			});
		},
		deleteExtField: function(item) {
			var vm = this;
			uni.showLoading({
				title: '请等待'
			});
			// 1.把同组的字段删掉
			var props = [];
			vm.formItems = vm.formItems.filter(n => {
				if (n.groupId != item.groupId) {
					return true;
				} else {
					props.push(n.prop);
					return false;
				}
			});
			vm.renameFileds(vm.formItems);
			// 2. 清空model里面的无效字段
			props.forEach(key => {
				delete vm.model[key];
				delete vm.rules[key];
				vm.$nextTick(function() {
					vm.getRefCmp('form1').setRules(vm.rules);
					uni.hideLoading();
				})
			});
		},
		codeChange(text) {
			this.validateTips = text;
		},
		getCode() {
			var vm = this;
			var uCode = vm.getRefCmp('uCode');
			var form1 = vm.getRefCmp('form1');
			if (uCode.canGetCode) {
				// 模拟向后端请求验证码
				form1.validateField('phone', function(res) {
					// debugger
					if (!res.length) {
						uni.showLoading({
							title: '正在获取验证码'
						});

						vm.getAndLoad('获取验证码',
							`/mobile/h5/covid19/apiZzsb/sendMsg.jsp?openId=${vm.openId}&phone=` + vm.model[
								'phone'],
							function(res) {
								uni.hideLoading();
								if (res.success) {
									uCode.start();
									uni.$u.toast('验证码已发送');
								} else {
									uni.$u.toast(res.msg || '验证码发送失败');
								}
							});
					}
				});
			}
		},
		afterFileRead: function(data, item) {
			var file = data.file[0];
			var vm = this;
			// item.fileList = [];
			vm.uploadFile(file.url, res => {
				if (!res.error) {
					item.fileList.push({
						path: res.path,
						url: vm.API_PREFIX + res.path
					});
					vm.model[item.prop] = item.fileList.map(n => n.path).join(',');
				} else {
					uni.$u.toast('上传失败');
				}
			});
			// item.fileList = [...data.file];
		},
		afterFileDelete: function(data, item) {
			item.fileList.splice(data.index, 1);
			this.model[item.prop] = item.fileList.map(n => n.path).join(',');
		},
		selecteProvinceCityArea(data, item) {
			item.provinceCityArea = data.code;
			this.model[item.prop] = data.name.join('-');
		},
		optionChecked: function(item, opindex) {
			item.options.forEach((n, i) => {
				n.active = i == opindex;
			});
			var checkItem = item.options[opindex];
			this.model[item.prop] = checkItem.value || checkItem.name;
			if (item.onChange) {
				this.handleItemOnChange(item);
			}
		},
		handleItemOnChange: function(field) {
			var vm = this;
			field.onChange.forEach((item => {
				if (item.type == 'changeRequired') {
					var targetField = vm.formItems.find(n => n.prop == item.field);
					if (targetField) {
						targetField.required = item.when.includes(vm.model[field.prop]);
					}
				} else if (item.type == 'changeHide') {
					var targetField = vm.formItems.find(n => n.prop == item.field);
					if (targetField) {
						targetField.hide = item.when.includes(vm.model[field.prop]);
					}
				}
			}));
		},
		openPicker: function(item) {
			this.currentProp = item.prop;
			var currentVal = this.model[item.prop];
			var hideKeyBorad = true;
			if (item.type == 'date') {
				if (currentVal) {
					this.datePickerModel = new Number(new Date(currentVal));
				} else {
					this.datePickerModel = new Number(new Date());
				}

				this.$nextTick(function() {
					this.showDatePicker = true;
				});
			}
			if (item.type == 'time') {
				if (currentVal) {
					this.timePickerModel = new Number(new Date(currentVal));
				} else {
					this.timePickerModel = new Number(new Date());
				}
				this.$nextTick(function() {
					this.showTimePicker = true;
				});
			} else if (item.type == 'areapicker') {
				this.showAreaPicker = true;
			} else if (item.type == 'xq-picker') {
				this.showXqPicker = true;
			} else if (item.type == 'picker') {
				item.showPicker = true;
			} else if (item.type == 'carNo') {
				this.trailerNo = this.model[this.currentProp];
				this.$nextTick(function() {
					this.showTrailerKeyboard = true;
				});
			} else if (item.type == 'tree-picker') {
				uni.setStorageSync('pickerOptions', item.options);
				uni.setStorageSync('currentPicked', item.value || []);
				uni.navigateTo({
					url: '/pages/tree/index?title=' + item.placeholder
				});
			} else if (item.address) {
				if (!this.model[item.prop] || (item.bindLnglat && !vm.model[item.bindLnglat[0]])) {
					this.openChoosemap(item);
				} else {
					hideKeyBorad = false; // 用户继续填写
				}
			} else {
				return;
			}
			hideKeyBorad && this.hideKeyboard();
		},
		openChoosemap: function(item) {
			var vm = this;
			uni.chooseLocation({
				success: res => {
					vm.model[item.prop] = res.address;
					if (item.bindLnglat) {
						vm.model[item.bindLnglat[0]] = res.latitude;
						vm.model[item.bindLnglat[1]] = res.longitude;
					}
				}
			});
		},
		openPickerConfirm: function(e, item) {
			var selectValue = e.value[0];
			if (typeof selectValue == 'string') {
				this.model[item.prop] = selectValue;
			} else {
				this.model[item.prop] = selectValue.name;
			}

			if (item.bindId) {
				this.model[item.bindId] = selectValue.id;
			}
			item.showPicker = false;
		},
		datePickerConfirm: function(value) {
			var item = this.formItems.find(n => (n.prop = this.currentProp));
			this.model[item.prop] = this.$Util.getFmtDate(new Date(value.value));
			this.showDatePicker = false;
		},
		treePickerConfirm: function(data) {
			var item = this.formItems.find(n => (n.prop = this.currentProp));
			this.model[item.prop] = data.map(n => n.name).join(',');
			item.value = data;
			if (item.bindId) {
				this.model[item.bindId] = data.map(n => n.id).join(',');
			}

		},
		timePickerConfirm: function(value) {
			var item = this.formItems.find(n => (n.prop = this.currentProp));
			this.model[item.prop] = this.$Util.getFmtDate(new Date(value.value), 'yyyy-MM-dd hh:mm');
			this.showTimePicker = false;
		},
		onPickerClose: function(item) {
			item.showPicker = false;
		},

		hideKeyboard: function() {
			uni.hideKeyboard();
		},
		getMobile: function (item) {
			debugger
		},
		generateModelAndRules: function() {
			var vm = this;
			var model = {};
			// 设置model
			this.formItems.forEach(item => {
				// item.key = vm.$Util.uuid();
				if (!item.prop) {
					return;
				}
				model[item.prop] = item.value || '';
				if (item.type == 'checkbox') {
					model[item.prop] = item.options[0].name;
				}
			});
			this.model = model;

			// 设置rule
			var rules = {};
			this.formItems.forEach(item => {
				if (!item.prop) {return;}
				rules[item.prop] = [];
				if (item.required) {
					if (!item.validatorWhen) {
						rules[item.prop].push({
							type: 'string',
							required: true,
							message: item.requireText || '此项为必填',
							trigger: ['blur', 'change']
						});
					} else {
						rules[item.prop].push({
							type: 'string',
							validator: (rule, value, callback) => {
								if (item.required) {
									return !!value.trim();
								} else {
									return true;
								}
							},
							message: '此项为必填',
							trigger: ['blur', 'change']
						})
					}
				}
				if (item.validator) {
					item.validator.forEach(n => {
						if (n == 'phone') {
							rules[item.prop].push({
								type: 'string',
								validator: (rule, value, callback) => {
									// debugger
									return (!item.required && !value) || uni.$u.test
										.mobile(value);
								},
								message: '手机号码不正确',
								trigger: ['change', 'blur']
							});
						} else if (n == 'idcard') {
							rules[item.prop].push({
								type: 'string',
								validator: (rule, value, callback) => {
									if (item.idcardValidatorWhen) {
										var isWhen = !item.idcardValidatorWhen || (vm
											.model[item.idcardValidatorWhen[0]] ==
											item.idcardValidatorWhen[1]);
										if (isWhen) {
											return !vm.$Util.idCardValidator(value);
										} else {
											return true;
										}
									} else {
                                       return !vm.$Util.idCardValidator(value);
                                    }

								},
								message: '身份证号码不正确',
								trigger: ['change', 'blur']
							});
						} else if (n == 'faceValidate') {
							rules[item.prop].push({
								type: 'string',
								validator: (rule, value, callback) => {
									var idCard = vm.model[item.getProp[0]];
									if (vm.$Util.analyzeIDCard(idCard)) {
										return !!value;
									} else {
										return true;
									}
								},
								message: item.requireText || '请完成认证',
								trigger: ['change', 'blur']
							});
						}
					});
				}
			});
			this.rules = rules;
			// #ifdef MP-WEIXIN
			this.$nextTick(() => {
				setTimeout(() => {
					vm.getRefCmp('form1').setRules(rules);
				}, 2000);
			});

			// #endif
		},
	}
}
